<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, getCurrentInstance, onMounted, reactive, nextTick } from 'vue'
import api from '@/api'; // 统一导入 API

const { proxy } = getCurrentInstance()

// 表单数据
const tableData = ref([])
const formInline = reactive({
    brand: '',
    productCode: '',
    pStatus: '',
    dateRange: []
})//搜索的内容 
const config = reactive({
    page: 1,
    pageSize: 20,
    brand: '',
    productCode: '',
    pStatus: '2',
    beginTime: '',
    endTime: ''
})

// 表单标签和选项
const tableLabel = reactive([
    {
        prop: 'brand',
        label: '品牌',
    },
    {
        prop: 'productCode',
        label: '商品款号'
    },
    {
        prop: 'retailPrice',
        label: '零售价'
    },
    {
        prop: 'color',
        label: '颜色'
    },
    {
        prop: 'inventory',
        label: '总计',
        width: 100
    },
    {
        prop: 'sizeF',
        label: 'F',
        width: 100
    },
    {
        prop: 'sizeXS',
        label: 'XS  /  26',
        width: 100
    },
    {
        prop: 'sizeS',
        label: 'S  /  27',
        width: 100
    },
    {
        prop: 'sizeM',
        label: 'M  /  28',
        width: 100
    },
    {
        prop: 'sizeL',
        label: 'L  /  29',
        width: 100
    },
    {
        prop: 'sizeXL',
        label: 'XL  /  30',
        width: 100
    },
    {
        prop: 'size2XL',
        label: '2XL  /  3',
        width: 100
    },
    {
        prop: 'size3XL',
        label: '3XL  /  32',
        width: 100
    },
    {
        prop: 'createTime',
        label: '首次入库时间',
        width: 110
    }
]);
let brandItems = reactive([
    { value: '路易丝', label: '路易丝' },
]);
let colorItems = reactive([
    { value: '黑色', label: '黑色' },
    { value: '白色', label: '白色' },
]);

// 状态
let isAddingBrand = ref(false);
let isAddingColor = ref(false);
let optionNameBrand = ref('');
let optionNameColor = ref('');
const dialogVisible = ref(false)
const action = ref('add')
const selectedRows = ref([]); // 用来存储选中的行
const multipleTable = ref(null);

// 获取库存数据
const getInventoryData = async () => {
    try {
        let data = await api.inventory.getInventoryData(config);
        tableData.value = data.records.map(item => ({
            ...item
        }));
        config.total = data.total;
    } catch (error) {
        ElMessage.error('获取库存数据失败，请稍后再试');
    }
};

// 处理搜索
const handleSearch = () => {
    // 清理输入，将只包含空格的字符串视为空字符串
    formInline.brand = formInline.brand.trim() || '';
    formInline.productCode = formInline.productCode.trim() || '';
    config.pStatus = formInline.pStatus ? formInline.pStatus.trim() : '2';

    if (Array.isArray(formInline.dateRange) && formInline.dateRange.length === 2) {
        let beginTimeString = formInline.dateRange[0];
        let endTimeString = formInline.dateRange[1];

        let beginTimeDate = new Date(beginTimeString);
        let endTimeDate = new Date(endTimeString);

        let year = beginTimeDate.getFullYear();
        let month = String(beginTimeDate.getMonth() + 1).padStart(2, '0');
        let day = String(beginTimeDate.getDate()).padStart(2, '0');
        config.beginTime = `${year}-${month}-${day} 00:00:00`;

        year = endTimeDate.getFullYear();
        month = String(endTimeDate.getMonth() + 1).padStart(2, '0');
        day = String(endTimeDate.getDate()).padStart(2, '0');
        config.endTime = `${year}-${month}-${day} 23:59:59`;
    } else {
        config.beginTime = ''
        config.endTime = ''
    }

    config.brand = formInline.brand
    config.productCode = formInline.productCode
    getInventoryData();
}

// 处理分页变化
const handleSizeChange = (pageSize) => {
    config.pageSize = pageSize
    getInventoryData()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
    config.page = page
    getInventoryData()
}

// 获取所有选中的行
const getSelectedRows = () => {
    return multipleTable.value.getSelectionRows();
};

// 处理选中行变化
const handleSelectionChange = (selection) => {
    selection.forEach(row => {
        if (row.inventory != null ) {
            ElMessage({
                message: '警告，只能勾选无库存商品',
                type: 'warning',
            })
            multipleTable.value.toggleRowSelection(row, false);
        }
    });
    selectedRows.value = multipleTable.value.getSelectionRows();
};

// 批量删除
const handleBatchDelete = async () => {
    selectedRows.value = getSelectedRows();
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要删除的行');
        return;
    }
    const ids = selectedRows.value.map(row => row.id);

    await ElMessageBox.confirm('此操作将永久删除选中的商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        try {
            await api.inventory.deleteBatch({ ids });
            ElMessage({
                type: 'success',
                message: '删除成功!',
            });
            getInventoryData();
        } catch (error) {
            ElMessage.error('删除失败: ' + error.message);
        }
    }).catch(() => { });
};

// 编辑界面按钮方法
const handleClose = () => {
    dialogVisible.value = false
    proxy.$refs['inventoryForm'].resetFields()
}
const handleCancel = handleClose;
const handleAdd = () => {
    dialogVisible.value = true
    action.value = "add"
}

// 品牌下拉框按钮方法
const addOption = (collection, optionInput, isAddingRef) => {
    // 添加选项的方法（复用）
    if (optionInput.value) {
        collection.push({
            label: optionInput.value,
            value: optionInput.value,
        });
        clearOption(optionInput, isAddingRef);
    }
};
const clearOption = async (optionInput, isAddingRef) => {
    // 清除输入框和添加状态的方法（复用）
    optionInput.value = '';
    isAddingRef.value = false;
};
const onAddBrandOption = () => {
    isAddingBrand.value = true;
};
const onConfirmBrand = () => {
    // 品牌下拉框的特定操作
    addOption(brandItems, optionNameBrand, isAddingBrand);
};
const clearBrand = () => {
    clearOption(optionNameBrand, isAddingBrand);
};
const onAddColorOption = () => {
    // 颜色下拉框的特定操作
    isAddingColor.value = true;
};
const onConfirmColor = () => {
    addOption(colorItems, optionNameColor, isAddingColor);
};
const clearColor = () => {
    clearOption(optionNameColor, isAddingColor);
};


// 新增/编辑界面的默认配置
const formInventory = reactive({
})
//表单校验规则
const rules = reactive({
    brand: [
        { required: true, message: '请选择品牌', trigger: 'change' },
    ],
    productCode: [
        { required: true, message: '请输入商品款号', trigger: 'blur' },
        { min: 3, max: 20, message: '商品款号长度在 3 到 20 个字符之间', trigger: 'blur' },
    ],
    retailPrice: [
        { required: true, message: '请输入零售价', trigger: 'blur' },
        { type: 'number', message: '零售价必须是数字', trigger: ['blur', 'change'] },
        // { min: 0, message: '零售价不能为负数', trigger: 'blur' },
    ],
    color: [
        { required: true, message: '请选择颜色', trigger: 'change' },
    ],
});
// 编辑功能
const handleEdit = (val) => {
    action.value = 'edit'
    dialogVisible.value = true
    nextTick(() => {
        Object.assign(formInventory, {
            ...val,
        })
    })
}

// 提交表单
const onSubmit = async () => {
    console.log(proxy)
    proxy.$refs['inventoryForm'].validate(async (valid) => {
        if (valid) {
            console.log('表单验证通过，发送请求...');
            try {
                await api.inventory.updateInventory(formInventory);
                dialogVisible.value = false;  // 关闭（新增/修改）页面
                ElMessage.success("修改成功")
                getInventoryData();
            } catch (error) {
                ElMessage.error('修改失败，请稍后再试');
            }
        } else {
            console.log('表单验证不通过');
            ElMessage.error('请检查表单中的错误并修正。');
        }
    });
}
// 生命周期钩子
onMounted(() => {
    getInventoryData()
})
</script>

<template>
    <div class="Inventory-header">
        <el-form :inline="true" :model="formInline"  @submit.native.prevent="handleSearch">
            <el-form-item label="商品品牌:">
                <el-input placeholder="请输入商品品牌" v-model="formInline.brand"  @input="handleSearch"></el-input>
            </el-form-item>
            <el-form-item label="商品款号:">
                <el-input placeholder="请输入商品款号" v-model="formInline.productCode"  @input="handleSearch"></el-input>
            </el-form-item>
            <el-form-item label="商品状态:" class="select-brand">
                <el-select v-model="formInline.pStatus" placeholder="全部"
                @change="handleSearch">
                    <el-option label="全部" value="2" />
                    <el-option label="有货" value="1" />
                    <el-option label="无货" value="0" />
                </el-select>
            </el-form-item>
            <el-form-item label="首次入库时间:">
                <el-date-picker v-model="formInline.dateRange" type="daterange" start-placeholder="开始日期"
                    end-placeholder="结束日期"  @change="handleSearch"/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
        </el-form>
        <div>
            <el-button type="primary" round @click="handle">批量出库</el-button>
            <el-button type="danger" round size="mini" @click="handleBatchDelete">
                批量删除
            </el-button>
        </div>
    </div>

    <div class="table">
        <div v-if="tableData.length === 0">
            <el-empty description="没有数据" />
        </div>
        <div v-else>
            <el-table :data="tableData" border   style="width: 100%" ref="multipleTable" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column type="index" width="50" />
                <!-- 基础信息 -->
                <el-table-column prop="brand" label="品牌" width="120" />
                <el-table-column prop="productCode" label="商品款号" width="120" />
                <el-table-column prop="retailPrice" label="零售价" width="120" />
                <el-table-column prop="color" label="颜色" width="100" />

                <!-- 分组：库存信息 -->
                <el-table-column label="库存" header-align="center" align="center">
                    <el-table-column prop="inventory" label="总计" width="100" />
                    <el-table-column prop="sizeF" label="F" width="100" />
                    <el-table-column prop="sizeXS" label="XS / 26" width="100" />
                    <el-table-column prop="sizeS" label="S / 27" width="100" />
                    <el-table-column prop="sizeM" label="M / 28" width="100" />
                    <el-table-column prop="sizeL" label="L / 29" width="100" />
                    <el-table-column prop="sizeXL" label="XL / 30" width="100" />
                    <el-table-column prop="size2XL" label="2XL / 31" width="100" />
                    <el-table-column prop="size3XL" label="3XL / 32" width="100" />
                </el-table-column>

                <!-- 其他信息 -->
                <el-table-column prop="createTime" label="首次入库时间" width="110" />

                <!-- 操作按钮 -->
                <el-table-column fixed="right" label="操作" min-width="120">
                    <template #default="scope">
                        <el-button type="primary" round plain size="mini" @click="handleEdit(scope.row)">
                            编辑
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>
    </div>
    <el-pagination v-model:current-page="config.page" v-model:page-size="config.pageSize" :page-sizes="[20, 30, 40]"
        size="small" :disabled="false" layout="total, sizes, prev, pager, next, jumper" :total="config.total" background
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <!-- 库存编辑界面 -->
    <el-dialog v-model="dialogVisible" :title="action == 'add' ? '新增' : '编辑'" width="35%" :before-close="handleClose">
        <el-form :inline="true" :model="formInventory" :rules="rules" ref="inventoryForm">
            <el-row>
                <el-col :span="12">
                    <el-form-item class="select-clean" label="品牌" prop="brand">
                        <el-select v-model="formInventory.brand" filterable placeholder="请选择">
                            <el-option v-for="item in brandItems" :key="item.value" :label="item.label"
                                :value="item.value" />
                            <template #footer>
                                <el-button v-if="!isAddingBrand" text bg size="small"
                                    @click="onAddBrandOption">+</el-button>
                                <template v-else>
                                    <el-input v-model="optionNameBrand" class="option-input" placeholder="创建新的品牌"
                                        size="small" />
                                    <el-button type="primary" size="small" @click="onConfirmBrand">添加</el-button>
                                    <el-button size="small" @click="clearBrand">取消</el-button>
                                </template>
                            </template>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="商品款号" prop="productCode">
                        <el-input v-model="formInventory.productCode" placeholder="请输入款号" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="零售价" prop="retailPrice">
                        <el-input v-model="formInventory.retailPrice" placeholder="请输入零售价" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item class="select-clean" label="颜色" prop="color">
                        <el-select v-model="formInventory.color" placeholder="请选择">
                            <el-option v-for="item in colorItems" :key="item.value" :label="item.label"
                                :value="item.value" />
                            <template #footer>
                                <el-button v-if="!isAddingColor" text bg size="small"
                                    @click="onAddColorOption">+</el-button>
                                <template v-else>
                                    <el-input v-model="optionNameColor" class="option-input" placeholder="创建新的颜色"
                                        size="small" />
                                    <el-button type="primary" size="small" @click="onConfirmColor">添加</el-button>
                                    <el-button size="small" @click="clearColor">取消</el-button>
                                </template>
                            </template>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row style="justify-content: flex-end">
                <el-form-item>
                    <el-button type="primary" @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="onSubmit">提交</el-button>
                </el-form-item>
            </el-row>
        </el-form>
    </el-dialog>
</template>

<style scoped lang="less">
.Inventory-header {
    display: flex;
    justify-content: space-between;
}

.table {
    position: relative;
    width: 100%;

    .pager {
        position: absolute;
        right: 10px;
        bottom: 30px;
    }

    .el-table {
        width: 100%;
        height: auto;
    }
}

.select-clean {
    display: flex;
}

.select-brand {
    width: 200px;
}
</style>